<?php
final class XFile{
	private $filename = null;
	
	public function __construct($filename){
		$this->filename = $filename;
	}
	
	public function canRead(){
		return is_readable($this->filename);
	}
	
	public function canWrite(){
		return is_writeable($this->filename);
	}
	
	public function create(){
		if($this->exists()){
			return true;
		}
		if(!file_exists(dirname($this->filename))){
			@mkdir(dirname($this->filename), 0777, true);
		}
		$file = @fopen($this->filename, "w+");
		if($file){
			@fclose($file);
			return true;
		}	
		XEventContext::singleton()->publish(new XLoggingEvent($this, WARN, "failed in creating file {$this->filename}"));
		return false;
	}
	
	public function delete(){
		if($this->isFile()){
			if(!@unlink($this->filename)
				&& $this->exists()){
				XEventContext::singleton()->publish(new XLoggingEvent($this, WARN, "failed in deleting file {$this->filename}"));
				return false;
			}
			return true;
		}
		if(!$this->isDirectory()){
			return false;
		}
		$children = $this->listFiles();
		foreach($children as $child){
			$child->delete();
		}
		if(!@rmdir($this->filename)
			&& $this->exists()){
			XEventContext::singleton()->publish(new XLoggingEvent($this, WARN, "failed in deleting directory {$this->filename}"));
			return false;
		}
		return true;
	}
	
	public function deleteOnExit(){
		register_shutdown_function(array($this, 'delete'));
	}
	
	public function exists(){
		return file_exists($this->filename);	
	}
	
	public function getName(){
		return basename($this->filename);
	}
	
	public function getParent(){
		return dirname($this->filename);
	}
	
	public function getPath(){
		return $this->filename;
	}
	
	public function isDirectory(){
		return is_dir($this->filename);
	}
	
	public function isFile(){
		return is_file($this->filename);
	}
	
	public function lastModified(){
		return filemtime($this->filename);
	}
	
	public function length(){
		return filesize($this->filename);
	}
	
	public function listFiles(){
		if(!$this->isDirectory()){
			return array();
		}
		$handler = @opendir($this->filename);
		if(!$handler){
			return array();
		}
		$files = array();
		while($file = @readdir($handler)){
			if(in_array($file, array('.', '..'))){
				continue;
			}
			$files[] = new XFile($this->filename.DIRECTORY_SEPARATOR.$file);
		}
	    @closedir($handler);	
	    return $files;	
	}
	
	public function mkdir(){
		if($this->exists()){
			return true;
		}
		if(!@mkdir($this->filename, 0777, true)
			&& !$this->exists()){
			XEventContext::singleton()->publish(new XLoggingEvent($this, WARN, "failed in creating directory {$this->filename}"));
			return false;
		}
		return true;
	}
	
	public function rename($newName){
		return @rename($this->filename, $newName);
	}
}
?>